<template>
  <div class="addProduct">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="grid-content bg-purple nav">
          <div class="title">产品类型列表</div>
          <Tree @changeProductCategory="changeProductCategory"></Tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="grid-content bg-purple content">
          <div class="title">{{ $store.state.productState.title }}</div>
          <div class="product-content">
            <el-form :model="product" :rules="rules" ref="product" label-width="90px" class="demo-ruleForm"
              size="small">
              <el-form-item label="所属分类" prop="categoryName">
                <span>{{ product.categoryName }}</span>
              </el-form-item>
              <el-form-item label="商品名称" prop="productName">
                <el-input v-model="product.productName"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="price">
                <el-input v-model="product.price"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="num">
                <el-input v-model="product.num"></el-input>
              </el-form-item>
              <el-form-item label="商品卖点" prop="sellPoint">
                <el-input v-model="product.sellPoint"></el-input>
              </el-form-item>

              <el-form-item label="上传图片">
                <ImageUpload @sendImage="sendImage" @removeImage="removeImage" ref="imageUpload" :fileList="fileList">
                </ImageUpload>
              </el-form-item>
              <el-form-item label="商品描述">
                <WangEditor @sendHtmlStr="sendHtmlStr" ref="wangEditor" :descs="product.descs"></WangEditor>
              </el-form-item>

              <el-form-item label="首页轮播推荐" prop="carousel" label-width="115px">
                <el-switch v-model="carousel" active-color="#13ce66" inactive-color="#f0f0f0" @change="onChange">
                </el-switch>
              </el-form-item>
              <el-form-item label="是否推荐商品" prop="recommend" label-width="115px">
                <el-switch v-model="recommend" active-color="#13ce66" inactive-color="#f0f0f0"> </el-switch>
              </el-form-item>
              <el-form-item label="是否上架商品" prop="status" label-width="115px">
                <el-switch v-model="status" active-color="#13ce66" inactive-color="#f0f0f0"> </el-switch>
              </el-form-item>

              <el-form-item>
                <div style="margin-bottom: 20px">
                  <el-button type="primary" @click="submitForm('product')">保存</el-button>
                  <el-button type="" @click="resetForm('product')">重置</el-button>
                  <el-button type="" @click="toProductList">取消</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Tree from '@/views/tree/index.vue'
import ImageUpload from '@/views/upload/image.vue'
import WangEditor from '@/views/editor/wang-editor.vue'
import { getProductById, addProduct,editProduct } from '@/api/product.js'
import { mapMutations } from 'vuex';
export default {
  components: {
    Tree,
    ImageUpload,
    WangEditor,
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      product: {
        id:'',
        categoryName: '',
        productName: '',
        price: '',
        num: '',
        sellPoint: '',
        images: '',
        descs: '',
        cid: '',
      },
      fileList: [],
      carousel: true,
      recommend: true,
      status: true,

      rules: {
        categoryName: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '商品价格必须为大于0的数字且最多两位小数', trigger: 'blur' },
          // { min: 0, message: '商品价格不能小于 3', trigger: 'blur' },
          // { max: 99999, message: '商品价格不能大于 99999', trigger: 'blur' },
        ],
        num: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '商品数量必须为正整数', trigger: 'blur' },
          // { min: 1, message: '商品数量不能小于 1', trigger: 'blur' },
          // { max: 99999, message: '商品数量不能大于 99999', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    const productId = this.$store.state.productState.productId;
    if (productId) {
      this.changeTitle('编辑商品');
      
      getProductById({ productId }).then(res => {
        const product = res.data;
        this.product=product;
        this.carousel = product.carousel == 1
        this.recommend = product.recommend == 1
        this.status = product.status == 1
        const imageList=this.product.images.split(',');
        this.fileList = imageList.map((url, index) => {
          return { uid: this.$uuidv4(), url: url };
        });
        console.log('this.product',this.product);
      })
    } else {
      this.changeTitle('添加商品');
    }
  },
  methods: {
    ...mapMutations('productState', ['changeTitle']),
    toProductList() {
      this.$router.push('/product/list')
    },
    onChange(val) { },
    sendHtmlStr(htmlStr) {
      this.product.descs = htmlStr
    },
    sendImage(uid,url) {
      this.fileList.push({ uid,url })
    },
    removeImage(uid) {
      this.fileList = this.fileList.filter((item) => item.uid != uid)
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.fileList.length == 0) {
            this.$showInfoMsg('请至少上传一张图片')
            return
          }
          // 使用 map 方法获取每个对象的 url 属性,并使用 join 方法将数组中的每个 url 用逗号拼接起来
          this.product.images = this.fileList.map((obj) => obj.url).join(',')
          this.product.carousel = this.carousel ? 1 : 0
          this.product.recommend = this.recommend ? 1 : 0
          this.product.status = this.status ? 1 : 0
          const product = this.product

          // 新增
          if(!this.product.id){
            addProduct(product).then((res) => {
              if (res.data) {
                setTimeout(() => {
                  this.$router.push('/product/list')
                  this.$message({
                    type: 'success',
                    message: '添加成功!',
                  })
                }, 500)
              }else{
                this.$message({
                    type: 'error',
                    message: '添加失败!',
                  })
              }
            })
          }
          // 修改
          else{
            console.log('this.product',this.product);
            editProduct(product).then(res=>{
              if (res.data) {
                setTimeout(() => {
                  this.$router.push('/product/list')
                  this.$message({
                    type: 'success',
                    message: '修改成功!',
                  })
                }, 500)
              }else{
                this.$message({
                    type: 'error',
                    message: '修改失败!',
                  })
              }
            })
          }
        } else {
          if (!this.product.categoryName) {
            this.$showInfoMsg('请点击左侧产品类型列表，选择一个商品分类')
          } else {
            this.$showInfoMsg('产品信息填写有误')
          }
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs.imageUpload.clearImageList();
      this.$refs.wangEditor.clearEditorHtml();
      this.product.descs='';  //使用了子组件，单独清空内容
      this.fileList = [] //使用了子组件，单独清空内容
      this.carousel = true
      this.recommend = true
      this.status = true
    },

    changeProductCategory(categoryName, cid) {
      this.product.categoryName = categoryName
      this.product.cid = cid
    },
  },
}
</script>

<style lang="less" scoped>
.addProduct {

  // border: 1px solid red;
  .nav {
    height: 600px;
    background-color: #fff;

    .title {
      background-color: skyblue;
      color: #fff;
      font-size: 14px;
      padding: 20px 0 20px 20px;
    }
  }

  .content {
    background-color: #fff;
    // height: 900px;

    .title {
      background-color: #eee;
      color: #000;
      font-weight: bold;
      padding: 10px 0 10px 10px;
    }
  }
}

.product-content {
  padding-top: 20px;
  padding-right: 20px;
}
</style>
